// Fill out your copyright notice in the Description page of Project Settings.


#include "CameraBaseCpp.h"

// Sets default values
ACameraBaseCpp::ACameraBaseCpp()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	CameraArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("Camera Arm"));
	CameraArm->SetupAttachment(RootComponent);

	FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("Follow Camera"));
	FollowCamera->SetProjectionMode(ECameraProjectionMode::Orthographic);
	FollowCamera->SetupAttachment(CameraArm);
}

// Called when the game starts or when spawned
void ACameraBaseCpp::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void ACameraBaseCpp::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	if (LocalPlayer == nullptr)
	{
		LocalPlayer = Cast<APlayerBaseCpp>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
		if (LocalPlayer != nullptr)
		{
			SetActorLocation(LocalPlayer->GetActorLocation() - FVector(XFromPlayer, 0.0, 0.0));
		}
		else
		{
			UE_LOG(LogTemp, Warning, TEXT("null"));
			return;
		}
	}
	FVector CameraToPlayer = FVector::ZeroVector;
	CameraToPlayer.X = 0.0;
	CameraToPlayer.Y = LocalPlayer->GetActorLocation().Y - GetActorLocation().Y;
	CameraToPlayer.Z = LocalPlayer->GetActorLocation().Z - GetActorLocation().Z;
	const FVector CameraLocation = GetActorLocation();
	const float Len = CameraToPlayer.Size();
	if (Len > RFromCenter)
	{
		SetActorLocation(CameraLocation + (Len - RFromCenter) * CameraToPlayer / CameraToPlayer.Size());
	}
}

